<script lang='ts' setup>
import { message } from 'ant-design-vue';
import {getWechat,watchScan} from '~/api/wechat'

let {registerModel} =useModel()

const{wechatModel}=storeToRefs(useModel())
let {switchLoginState} =useUser()

let lock=ref(true)  // 防抖
let qrcodeUrl=ref<any>(null)
let timer=ref<any>(null)
// 二维码地址接口请求
const getQrcode=async()=>{
  if(lock.value){
    lock.value =false
    const res =await getWechat()
    if(res.code===0){
      qrcodeUrl.value=res.data.qrcodeUrl
      lock.value=true
      // 轮询请求是否扫码接口
      timer.value=setInterval(()=>watchScanDate(res.data.ticket),3000)
    }
  }
}
await getQrcode()

// 轮询接口请求
const watchScanDate=async(ticket:string)=>{
  const res =await watchScan(ticket)
  if(res.code===0){
    switchLoginState(res.data)
    wechatModel.value=false
    registerModel.base=false
    clearInterval(timer.value)
    message.success('登录成功')
  }
  // 如果通过手动关闭二维码，清除定时器
  watch(()=>wechatModel.value,(val)=>!val&&clearInterval(timer.value))
}

</script>

<template>
  <div flexc flex-col mt-50px>
    <img w-200px h-200px :src='qrcodeUrl' />
    <div flexc mt-26px>
      <img src="/images/wechat_icon.png" cursor-pointer mr-2px w-34px h-34px />
      <span text-18px color="#555555">使用微信扫一扫登录</span>
    </div>
  </div>
</template>

<style lang='less' scoped>

</style>